const fs = require('fs');
const path = require('path');
const fetch = require('node-fetch');

const DIR = '/Users/liuzy/Pictures/bing/';
const SIZE = ['UHD', '4096×2160', '2560x1440', '1920x1080', '1280×720'][0];

const site = 'https://cn.bing.com/HPImageArchive.aspx?format=js&n=10';
if (!fs.existsSync(DIR)) {
    fs.mkdirSync(DIR);
}
fetch(site).then(res => res.json()).then(async (json) => {
    for (let i in json.images) {
        const img = json.images[i];
        const dst = path.join(DIR, img.copyright.split(' (©')[0].replace(/\//g, ',') + '.jpg');
        const url = `https://cn.bing.com${img.url.split('_1920x1080.jpg')[0]}_${SIZE}.jpg`;
        console.log(url, '=>', dst);
        if (!fs.existsSync(dst)) {
            await fetch(url).then(res => res.body.pipe(fs.createWriteStream(dst)));
        }
    }
});